package com.example.yuwei.mediaplayer.module;

import android.media.MediaPlayer;
import android.util.Log;

import com.example.yuwei.mediaplayer.presenter.MusicPresenter;

import java.io.IOException;

public class MusicPlayer implements MusicPlayerModule {
    private MediaPlayer mediaPlayer;
    private boolean isOver = false;
    private String TAG = "musicPlayer";
    private MusicPresenter musicPresenter;
    private static MusicPlayer musicPlayer;

    public MusicPlayer() {
        mediaPlayer = new MediaPlayer();
    }

    public static MusicPlayer getInstance() {
        if (musicPlayer == null) {
            musicPlayer = new MusicPlayer();
        }
        return musicPlayer;
    }

    public void firstOpen(String url) {
        try {
            Log.e(TAG, "firstOpen: "+url);
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.e(TAG, "onCompletion:");
                musicPresenter = MusicPresenter.getInstance();
                musicPresenter.next();
            }
        });
    }

    @Override
    public void play(String url) {
        Log.i(TAG, "play+++++++++++++++" + url);
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pauseOrplay() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            Log.i(TAG, "playor:Pause ");
        } else {
            Log.i(TAG, "playor:Play ");
            mediaPlayer.start();
        }
    }

    @Override
    public void progress(int time) {

        mediaPlayer.seekTo(time);
        mediaPlayer.start();
    }

    @Override
    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    @Override
    public boolean isPlaying() {

        return mediaPlayer.isPlaying();
    }

    @Override
    public void stop() {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        Log.i(TAG, "media player stop ");
    }

}
